package com.xinghou.platform.server.api.bussiness.impl;

import com.xinghou.platform.dao.main.*;
import com.xinghou.platform.entity.req.MsgInfoReq;
import com.xinghou.platform.entity.resp.ActiveInfo;
import com.xinghou.platform.entity.resp.MsgInfo;
import com.xinghou.platform.model.main.*;
import com.xinghou.platform.server.api.bussiness.LoginHistoryService;
import com.xinghou.platform.server.api.bussiness.MsgInfoBusinessService;
import com.xinghou.platform.server.mq.MqMessage;
import com.xinghou.platform.util.GeohashUtil;
import com.xinghou.platform.util.JsonUtil;
import com.xinghou.platform.util.StringUtils;
import com.xinghou.platform.util.map.GeoHashUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("msginfoService")
public class MsgInfoBusinessServiceImpl implements MsgInfoBusinessService {
	@Resource
	private StoreDAO storeDAO;
	@Resource
	private UserDAO userDAO;
	@Resource
	private UserGeoDAO userGeoDAO;
	@Resource
	private LoginHistoryDAO loginHistoryDAO;

	@Resource
	private LoginHistoryService loginHistoryService;

	@Resource
	private MessageDAO messageDAO;
	@Resource
	private CityDAO cityDAO;
	@Resource
	private NoticeDAO noticeDAO;
	@Resource
	private SharedCardDAO sharedCardDAO;
	@Resource
	private MqMessage mqMessage;

	/*private static HashMap<Integer, String> msgmap = new HashMap<Integer,String>();
	*/
	/**
	 * 1表示成功   0表示失败
	 */
	public String updateUserLocation(MsgInfoReq msgInfoReq) {
		Double[] pos = new Double[2];
		
			pos[0] = Double.valueOf(msgInfoReq.getLng());
			pos[1] = Double.valueOf(msgInfoReq.getLat());
			User user = userDAO.getUserById(Integer.valueOf(msgInfoReq.getUserid()));
				if (user != null) {
					UserGeo usergeo = userGeoDAO.getUserGeoById(user.getUserid());
					int type = 0;
					if (usergeo == null) {
						usergeo = new UserGeo();
						type = 1;
					}
					usergeo.setCitycode(msgInfoReq.getCitycode());
					usergeo.setLatitude(Double.valueOf(msgInfoReq.getLat()));
					usergeo.setLongitude(Double.valueOf(msgInfoReq.getLng()));
					usergeo.setAdcode(msgInfoReq.getAdcode());
					if (StringUtils.isNotBlank(msgInfoReq.getLocal())) {
						usergeo.setLocation(msgInfoReq.getLocal());
					}
					//usergeo.setGeoHash(GeohashUtil.encodeBin(Double.valueOf(msgInfoReq.getLat()), Double.valueOf(msgInfoReq.getLng()), false));
					usergeo.setGeoHash(GeoHashUtil.encode(Double.valueOf(msgInfoReq.getLat()), Double.valueOf(msgInfoReq.getLng())));
					usergeo.setGeoLong(GeohashUtil.encodeLong(Double.valueOf(msgInfoReq.getLat()), Double.valueOf(msgInfoReq.getLng())));
					usergeo.setUpdateTime(System.currentTimeMillis());
					if (type == 0)
						userGeoDAO.updateUserGeo(usergeo);
					LoginHistory loginHistory = new LoginHistory();
					loginHistory.setLoginTime(System.currentTimeMillis());
					loginHistory.setUserId(Integer.valueOf(msgInfoReq.getUserid()));
					loginHistory.setLatitude(Double.valueOf(msgInfoReq.getLat()));
					loginHistory.setLongitude(Double.valueOf(msgInfoReq.getLng()));
					loginHistory.setDeviceToken(msgInfoReq.getDeviceid());
					loginHistoryService.saveLoginHistory(loginHistory);
				}
		mqMessage.sendMessageUser(msgInfoReq.getUserid(),true);

			return "1";
	}

	@Override
	public void  sendUpdateGPSMessage(MsgInfoReq msgInfoReq) {
		String userid=msgInfoReq.getUserid();
		User user=userDAO.getUserById(Integer.parseInt(userid));
		if(user==null){
			return;
		}
		String message= JsonUtil.toJson(msgInfoReq);
		mqMessage.sendMessageGPS(message);
	}

	@Override
	public int sendNewMsg(MsgInfoReq msgInfoReq) {
		UserRelationFrom userRelationFrom = new UserRelationFrom();
		userRelationFrom.setFromuserid(Integer.valueOf(msgInfoReq.getUserid()));
		userRelationFrom.setTouserid(Integer.valueOf(msgInfoReq.getTouserid()));
		UserRelationTo userRelationTo = new UserRelationTo();
		userRelationTo.setFromuserid(Integer.valueOf(msgInfoReq.getUserid()));
		userRelationTo.setTouserid(Integer.valueOf(msgInfoReq.getTouserid()));
		Message message = new Message();
		message.setCreateTime(System.currentTimeMillis());
		if(Integer.valueOf(msgInfoReq.getMsgType())>1){
			if(msgInfoReq.getMsgType().equals("3")){
				message.setJumpUrl(msgInfoReq.getLinkurl());
			}
			if(msgInfoReq.getMsgType().equals("4")){
				message.setJumpNativePage(msgInfoReq.getNativelink());
			}
		}
		//先默认为文本
		message.setMsgType((short)1);
		//先默认为用户
		message.setOrigin((short)1);
		message.setStatus((short)0);
		message.setText(msgInfoReq.getContent());
		message.setSenderId(Integer.valueOf(msgInfoReq.getUserid()));
		message.setReceiverId(Integer.valueOf(msgInfoReq.getTouserid()));
		return messageDAO.saveMessage(message);
	}
	public List<MsgInfo> getNewMsg(MsgInfoReq msgInfoReq){
		List<Message> messageList = messageDAO.queryMsg(Integer.valueOf(msgInfoReq.getUserid()), 
				Integer.valueOf(msgInfoReq.getTouserid()),-1,0,Integer.valueOf(msgInfoReq.getFromno()),20);
		
		List<MsgInfo> msgInfolist = new ArrayList<MsgInfo>();
		MsgInfo msgInfo = new MsgInfo();
		for (int i = 0; i < messageList.size(); i++) {
			String text="";
			msgInfo = new MsgInfo();
			msgInfo.setMsgType(messageList.get(i).getMsgType().toString());
			
			if(StringUtils.isNotBlank(messageList.get(i).getText())){
				text = messageList.get(i).getText();
			}
			
			if(StringUtils.isNotBlank(messageList.get(i).getJumpUrl())){
				msgInfo.setContent(text+messageList.get(i).getJumpUrl());
			}else if(StringUtils.isNotBlank(messageList.get(i).getJumpNativePage())){
				msgInfo.setContent(text+messageList.get(i).getJumpNativePage());
			}else{
				msgInfo.setContent(text);
			}
			

			msgInfo.setFromUserId(messageList.get(i).getSenderId()+"");
			msgInfo.setToUserId(messageList.get(i).getReceiverId()+"");
			
			msgInfo.setCreatetime(messageList.get(i).getCreateTime().toString());
			msgInfo.setMsgid(messageList.get(i).getMsgId()+"");
			msgInfolist.add(msgInfo);
			
			if(messageList.get(i).getReceiverId().toString().equals(msgInfoReq.getTouserid())){

				messageDAO.updateMessage(messageList.get(i));messageList.get(i).setStatus((short)1);
			}
			
		}
		return msgInfolist;
	}

	public int countMsg(MsgInfoReq msgInfoReq){
		return messageDAO.queryMsgCount(null, Integer.valueOf(msgInfoReq.getUserid()), (short)1, 0);
	}

	@Override
	public List<Notice> getNoticeList(MsgInfoReq msgInfoReq) {
		// TODO Auto-generated method stub
		return noticeDAO.getNoticeList(-1, Integer.valueOf(msgInfoReq.getUserid()), -1, 0, 1);
	}

	@Override
	public List<ActiveInfo> getSystemNoteList(MsgInfoReq msgInfoReq) {
		ActiveInfo activeInfo = new ActiveInfo();
		List<ActiveInfo> activeInfoList = new ArrayList<ActiveInfo>();
		List<Notice> noticelist = noticeDAO.getNoticeList(-1, Integer.valueOf(msgInfoReq.getUserid()), 0, Integer.valueOf(msgInfoReq.getFromno().equals("-1")?"0":msgInfoReq.getFromno()), 20);
		Notice notice = new Notice();
		String text="";
		for (int i = 0; i < noticelist.size(); i++) {
			activeInfo = new ActiveInfo();
			activeInfo.setActiveid(noticelist.get(i).getNoticeId()+"");
			activeInfo.setActiveTag(noticelist.get(i).getTitle());
			activeInfo.setActiveDate(noticelist.get(i).getCreateTime().toString());
			
			if(StringUtils.isNotBlank(noticelist.get(i).getText())){
				text = noticelist.get(i).getText();
			}
			
			if(StringUtils.isNotBlank(noticelist.get(i).getJumpUrl())){
				activeInfo.setActiveMsg(text+noticelist.get(i).getJumpUrl());
			}else if(StringUtils.isNotBlank(noticelist.get(i).getJumpNativePage())){
				activeInfo.setActiveMsg(text+noticelist.get(i).getJumpNativePage());
			}else{
				activeInfo.setActiveMsg(text);
			}

			notice = noticeDAO.getNoticeById(Integer.parseInt(noticelist.get(i).getNoticeId()));
			notice.setStatus("1");
			noticeDAO.updateNotice(notice);
			activeInfoList.add(activeInfo);
		}
		
		return activeInfoList;
	}
	
	/**
	 * 星后小秘书
	 * @param msgInfoReq
	 * @return
	 */
	public List<ActiveInfo> getSystemCoustomNoteList(MsgInfoReq msgInfoReq) {
		ActiveInfo activeInfo = new ActiveInfo();
		List<ActiveInfo> activeInfoList = new ArrayList<ActiveInfo>();
		/*int num = Integer.valueOf(msgInfoReq.getFromno());
		if(num == -1){
			num = 0;
		}
		List<Notice> noticelist = noticeDAO.getNoticeList(99999999, Integer.valueOf(msgInfoReq.getUserid()), 0, num, 20);
		Notice notice = new Notice();
		for (int i = 0; i < noticelist.size(); i++) {
			String text="";
			activeInfo = new ActiveInfo();
			activeInfo.setActiveid(noticelist.get(i).getNoticeId()+"");
			activeInfo.setActiveTag(noticelist.get(i).getTitle());
			activeInfo.setActiveDate(noticelist.get(i).getCreateTime().toString());
			
			if(StringUtils.isNotBlank(noticelist.get(i).getText())){
				text = noticelist.get(i).getText();
			}
			
			activeInfo.setActiveMsg(text);
			
			if(StringUtils.isNotBlank(noticelist.get(i).getJumpNativePage()))
				activeInfo.setActiveNative(noticelist.get(i).getJumpNativePage());
			
			if(StringUtils.isNotBlank(noticelist.get(i).getJumpUrl()))
				activeInfo.setActiveUrl(noticelist.get(i).getJumpUrl());
			

			if(noticelist.get(i).getType()==0)
				noticelist.get(i).setStatus(1);
			else{
				if(noticelist.get(i).getType()==1){
					noticelist.get(i).setCreateTime(noticelist.get(i).getCreateTime());
				}else if(noticelist.get(i).getType()==2){
					noticelist.get(i).setCreateTime(noticelist.get(i).getCreateTime());
				}else{
					noticelist.get(i).setCreateTime(noticelist.get(i).getCreateTime());
				}*//*
			}
			
			noticeDAO.updateNotice(noticelist.get(i));
			activeInfoList.add(activeInfo);
		}
		*/
		return activeInfoList;
	}
	
	/**
	 * 增加系统消息 1表示注册成功 2 用户成功绑定QQ应用 3 用户成功绑定微信应用 4 用户成功绑定微博应用 5 评分 （自然月）
	 * 6 会员卡信息审核下架 7美记审核下架 8用户的资本资料的生日 (年) 9用户接受第一条私聊消息 10 用户第一次成功发布晒/蹭卡信息
	 * @param userid
	 * @param msgtype
	 * @return
	 */
	public int addSystemNote(Integer userid,String shareId,int msgtype){
		/*Notice notice = new Notice();
		notice.setReceiverId(userid);
		notice.setSenderId(99999999);
		notice.setStatus(0);
		boolean bool = true;
		int result = 0;
		switch (msgtype) {
		case 1:
			if(msgmap.size()<7){
				loadResource();
			}
			for(int i=11;i<18;i++){
				notice.setTitle(String.valueOf(i));
				notice.setCreateTime(System.currentTimeMillis());
				notice.setType(0);
				notice.setText(msgmap.get(i));
				if(noticeDAO.getNoticeByTitle(String.valueOf(i), userid)!=null){
					bool = false;
				}else{
					result = noticeDAO.saveNotice(notice);
					bool = false;
				}
			}
			break;
		case 2:
			notice.setTitle("2");
			notice.setCreateTime(System.currentTimeMillis());
			notice.setType(0);
			notice.setText("哈哈，你已成功绑定QQ应用，为了确保您的账号安全，请不要随意泄露你的相关信息哦");
			if(noticeDAO.getNoticeByTitle("2", userid)!=null){
				bool = false;
			}
			break;
		case 3:
			notice.setTitle("3");
			notice.setCreateTime(System.currentTimeMillis());
			notice.setType(0);
			notice.setText("哈哈，你已成功绑定微信应用，为了确保您的账号安全，请不要随意泄露你的相关信息哦");
			if(noticeDAO.getNoticeByTitle("3", userid)!=null){
				bool = false;
			}
			break;
		case 4:
			notice.setTitle("4");
			notice.setCreateTime(System.currentTimeMillis());
			notice.setType(0);
			notice.setText("哈哈，你已成功绑定微博应用，为了确保您的账号安全，请不要随意泄露你的相关信息哦");
			if(noticeDAO.getNoticeByTitle("4", userid)!=null){
				bool = false;
			}
			break;
		case 5:
			notice.setTitle("5");
			notice.setCreateTime(System.currentTimeMillis());
			notice.setType(2);
			notice.setText("主人，小秘的服务还算周到吧！能移步App Store/Android给我五星好评么？");
			if(noticeDAO.getNoticeByTitle("5", userid)!=null){
				bool = false;
			}
			break;
		case 6:
			notice.setTitle("6");
			notice.setCreateTime(System.currentTimeMillis());
			notice.setType(0);
			SharedCard sharedCard=null;
			//SharedCard sharedCard = sharedCardDAO.getSharedCardBycardId(Integer.valueOf(shareId));
			//notice.setText("通知：你于"+DateUtils.getZhCNDate(DateUtils.getSingleNumDate(sharedCard.getCreateTime()))+"发布的”"+storeDAO.getStoreBystoreId(sharedCard.getStoreId()).getName()+"“的晒卡信息/蹭卡信息，已通过审核下架");
			sharedCard = null;
			break;
		case 7:
			notice.setTitle("7");
			notice.setCreateTime(System.currentTimeMillis());
			notice.setType(0);
			sharedCard = null;
			break;
		case 9:
			notice.setTitle("9");
			notice.setCreateTime(System.currentTimeMillis());
			notice.setType(0);
			notice.setText("你有一条私聊信息，请点击查看。收到的私聊信息都会归类在消息列表页，点击<私聊>进行查看、回复、删除等操作");
			if(noticeDAO.getNoticeByTitle("9", userid)!=null){
				bool = false;
			}
			break;
		default:
			notice.setTitle("10");
			notice.setCreateTime(System.currentTimeMillis());
			notice.setType(0);
			notice.setText("恭喜你成功发布折扣卡共享信息，借卡人会通过私聊联络你，请及时查收私聊信息，确保折扣卡共享成功。星小秘");
			//notice.setJumpNativePage("1");
			if(noticeDAO.getNoticeByTitle("10", userid)!=null){
				bool = false;
			}
			break;
		}
		if(bool){
			notice.setAttachId(0);
			result = noticeDAO.saveNotice(notice);
		}*/
		return 0;
	}

	@Override
	public int getCardStatus(Integer userid, Integer cardid, Integer type) {
		return 0;
	}


	private static void loadResource()
	{
		Map<Integer,String> msgmap = new HashMap<Integer,String>();
		msgmap.put(11, "主人，你终于来了，小秘在此等候多时了，接下来请允许小秘给你介绍星后的功能：");
		msgmap.put(12, "如果主人有闲置的美业折扣卡，请共享出来借给星友去消费吧，可以销卡套现哦！");
		msgmap.put(13, "如果主人没有美业折扣卡，可以去借星友共享出来的折扣卡哦，便宜、省钱、实惠！");
		msgmap.put(14, "如果主人在美业消费过程中，碰到欺骗、强行推销及骚扰等遭遇，可以直接将其匿名曝光哦！");
		msgmap.put(15, "当然，主人那么多的美照和美丽秘籍，也可以与星友一起分享哦！");
		msgmap.put(16, "最后，小秘悄悄的告诉主人，时尚的用户才玩星后，那么多美女帅哥，主人就不想尝试认识下？");
		msgmap.put(17, "主人在使用过程中如遇到问题，可以点击左下角《用户攻略》进行查询哦，如依然找不到你需要的答案，记得与小秘私聊哦！反正小秘一直都很寂寞的。");
	}
}
